﻿using System;
using System.Reflection.Metadata;
using Api.Model;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;

namespace Api.Model
{
    public class EfDemoContext : DbContext
    {
        public DbSet<User> Users { get; set; }
        public DbSet<Admin> Admins { get; set; }

        public DbSet<Post> Posts { get; set; }
        public DbSet<Comment> Comments { get; set; }
        public DbSet<Message> Messages { get; set; }
        
        public DbSet<UserBlockList> UserBlockList { get; set; }
        // 带参数的构造函数
        public EfDemoContext(DbContextOptions<EfDemoContext> options) : base(options)
        {

        }

        // 无参构造器
        // 这通常是为了支持迁移和设计时工具，但在运行时不会被使用
        public EfDemoContext()
        {

        }

        // 设计时工具使用的工厂类
        internal class EfDemoContextFactory : IDesignTimeDbContextFactory<EfDemoContext>
        {
            public EfDemoContext CreateDbContext(string[] args)
            {
                var optionsBuilder = new DbContextOptionsBuilder<EfDemoContext>();
                optionsBuilder.UseMySql("server=localhost;user=root;password=123456;database=bbs;", new MySqlServerVersion(new Version(8, 0, 33)));

                return new EfDemoContext(optionsBuilder.Options);
            }
        }

        // 运行时配置，可选
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseMySql("server=localhost;user=root;password=123456;database=bbs;", new MySqlServerVersion(new Version(8, 0, 33)));
            }
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<User>(e => { e.Property(u => u.id).ValueGeneratedOnAdd(); });
            modelBuilder.Entity<Admin>(e => { e.Property(a => a.id).ValueGeneratedOnAdd(); });
            // modelBuilder.Entity<Post>().HasKey(p => p.id);
            // modelBuilder.Entity<Comment>().HasKey(c => c.id);
            modelBuilder.Entity<Post>(entity =>
            {
                //配置主键为数据库新增时生成(自增主键)
                entity.Property(p => p.id).ValueGeneratedOnAdd();

                //配置 Post-Comment 的一对多关系
                //entity.HasMany(p => p.Comments)
                //.WithOne(c => c.Post)
                //.HasForeignKey(c => c.postId);
            });

            //配置主键为数据库新增时生成(自增主键)
            modelBuilder.Entity<Comment>()
                .Property(c => c.id)
                .ValueGeneratedOnAdd();
                
            modelBuilder.Entity<UserBlockList>()
                .HasKey(ubl => new { ubl.UserId, ubl.BlockedId }); // 配置复合主键

            base.OnModelCreating(modelBuilder);
            // 在这里配置模型
        }
    }
}
